package com.be.beadmin.design.controller;

import com.alibaba.excel.EasyExcel;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.design.dto.input.StandFileInfoByStandTypeIdAndCategoryPage;
import com.be.beadmin.design.dto.input.StandFileInfoDto;
import com.be.beadmin.design.dto.output.StandFileInfoEx;
import com.be.beadmin.design.entity.StandFileInfo;
import com.be.beadmin.design.repository.StandFileInfoRepository;
import com.be.beadmin.design.service.StandFileInfoService;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.service.impl.MinioService;
import com.google.common.io.ByteStreams;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
* @author Jiahao Liu
* @date 2023-02-16
**/
@Api(tags = {"设计管理-标准柜体附件"})
@RestController
public class StandFileInfoController {

    @Autowired
    private  StandFileInfoService standFileInfoService;

    @Autowired
    private StandFileInfoRepository standFileInfoRepository;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();


    private String bucketName = "standfile";

    @ApiOperation("切换BOM或图纸状态。（启用的附件id,柜体id，分类）")
    @PostMapping(value = "/design/switchStandFileInfo")
    public ResultModel switchStandFileInfo(
            @ApiParam(value = "附件id",required = true) @RequestParam String standFileInfoId,
            @ApiParam(value = "标准柜体id",required = true) @RequestParam String standTypeId,
            @ApiParam(value = "附件类型",required = true) @RequestParam String category,
            @ApiParam(value = "状态",required = true) @RequestParam int status)  {

        try {
            standFileInfoService.switchStandFileInfo(standFileInfoId,standTypeId,category,status);
            return ResultModel.success("启用成功") ;
        } catch (BeadminException e) {
            return ResultModel.error(-1,e.getMessage());
        } catch (Exception e) {
            return ResultModel.error(-2,e.getMessage());
        }


    }


    @ApiOperation("获取标准柜体附件分页信息")
    @PostMapping(value = "/design/getStandFileInfoByPage")
    public ResultModel getStandFileInfoByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(standFileInfoService.getStandFileInfoByPage(pageEntity)) ;
    }

    @ApiOperation("获取指定标准柜体BOM或图纸分页信息(标准柜ID，分类（BOM或者其他)")
    @PostMapping(value = "/design/getStandFileInfoByStandTypeIdAndCategoryPage")
    public ResultModel getStandFileInfoByStandTypeIdAndCategoryPage(@RequestBody StandFileInfoByStandTypeIdAndCategoryPage standFileInfoByStandTypeIdAndCategoryPage)  {

        try {
            return ResultModel.success( standFileInfoService.getStandFileInfoByStandTypeIdAndCategoryPage(standFileInfoByStandTypeIdAndCategoryPage)) ;
        } catch (BeadminException e) {
            return ResultModel.error(-1,e.getMessage());
        } catch (Exception e) {
            return ResultModel.error(-2,e.getMessage());
        }

    }

    @ApiOperation("获取标准附件类型（不用）")
    @PostMapping("/design/getStandFileType")
    public ResultModel getFileType(){
        return ResultModel.success(standFileInfoService.getStandFileType());
    }

//    @ApiOperation("新增标准柜体附件")
//    @PostMapping("/design/addStandFileInfo")
//    public ResultModel addStandFileInfo(@ApiParam(value = "柜体类型",required = true) @RequestParam String standTypeDesc,
//                                        @ApiParam(value = "附件类型",required = true) @RequestParam String category,
//                                        @ApiParam(value = "流水号") @RequestParam(required = false) String serialNo,
//                                        @ApiParam(value = "备注") @RequestParam(required = false) String memo){
//        standFileInfoService.addStandFileInfo(standFileInfoDto);
//        return ResultModel.success(ResultModel.ADD);
//    }

    @ApiOperation("删除标准柜体附件")
    @PostMapping("/design/delStandFileInfo")
    public ResultModel delStandFileInfo(@RequestBody StandFileInfoDto standFileInfoDto){
        standFileInfoService.delStandFileInfo(standFileInfoDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }



    @ApiOperation("导出")
    @PostMapping("/design/exportStandFileInfo")
    public void exportStandFileInfo(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<StandFileInfoEx> standFileInfoPage = standFileInfoService.getStandFileInfoByPage(pageEntity);
        List<StandFileInfoEx> standFileInfoExes = standFileInfoPage.getContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("StandFileInfo接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), StandFileInfoEx.class).sheet("sheet1").doWrite(standFileInfoExes);
    }

    @ApiOperation("判断bucket是否存在")
    @PostMapping ("/design/bucketExist")
    public ResultModel bucketExist(@ApiParam(value = "bucketName")@RequestParam String bucketName) throws InvalidPortException, InvalidEndpointException {
        boolean exists = minioUtil.bucketExists(bucketName);
        return ResultModel.success(exists);
    }

    @ApiOperation("获得pdf、图片的预览url")
    @PostMapping ("/design/getPreviewUrl")
    public ResultModel getPreviewUrl(@RequestBody StandFileInfoDto standFileInfoDto) throws Exception {
        String previewUrl = standFileInfoService.getPreviewUrl(standFileInfoDto);
        return ResultModel.success(previewUrl);
    }

    @ApiOperation("下载BOM模版")
    @GetMapping("/design/downloadStandardBom")
    @ResponseBody
    public void downloadStandardBom(HttpServletResponse response) throws Exception {
//        standFileInfoService.downloadFile(bucketName,fileCode,response);
        try {

            String standardBomName= "bom导入模板-20230816-v1.0.xls";
            String standardBomBucket="beadmin";
            InputStream inputStream = minioService.downloadOne(standardBomBucket, standardBomName);
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-disposition", "attachment;filename= "+standardBomName);
            response.addHeader("Content-Type", "text/plain;charset=utf-8");
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            ServletOutputStream os = response.getOutputStream();

            ByteStreams.copy(inputStream, os);
            os.flush();
            // return  ResultModel.success("下载成功");
        } catch (Exception e) {
            // return ResultModel.error(99,"文件读取异常");
        }
    }


    @ApiOperation("附件下载(图纸、bom等)")
    @GetMapping("/design/downloadFile")
    @ResponseBody
    public void downloadFile(@ApiParam(value = "standFileId")@RequestParam String standFileId,
                             HttpServletResponse response) throws Exception {
//        standFileInfoService.downloadFile(bucketName,fileCode,response);

        standFileInfoService.downloadStandFile(standFileId,response);

    }

    @ApiOperation("创建bucket")
    @GetMapping("/design/createBucket")
    public ResultModel createBucket(@ApiParam(value = "bucketName")@RequestParam String bucketName) throws Exception {
        minioUtil.createBucketName(bucketName);
        return ResultModel.success("创建成功");
    }

    @ApiOperation("标准柜体根据文件编码获取该文件所有信息")
    @PostMapping(value = "/design/getFileByFileCode")
    public ResultModel getFileByFileCode(@ApiParam(value = "文件编码",required = true) @RequestParam String fileCode)  {
        return ResultModel.success(standFileInfoService.getFileByFileCode(fileCode)) ;
    }


}